//
//  DeviceDCViewController.m
//  sentorise
//
//  Created by admin on 2025/8/28.
//

#import "DeviceDCViewController.h"
#import "GlobalDefine.h"
#import "BTManager.h"
#import "ProgressHUD.h"
#import "HelpCenterViewController.h"

@interface DeviceDCViewController ()

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topSpace;

@property (weak, nonatomic) IBOutlet UIButton *cdfSW;
@property (weak, nonatomic) IBOutlet UIButton *cdjrSW;
@property (weak, nonatomic) IBOutlet UIButton *restartSW;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *restartH;
@property (weak, nonatomic) IBOutlet UILabel *restartLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *restartTop;
@property (weak, nonatomic) IBOutlet UILabel *restartStateLabel;

@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *item1TitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *item2TitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *item2DescLabel1;
@property (weak, nonatomic) IBOutlet UILabel *item2DescLabel2;
@property (weak, nonatomic) IBOutlet UILabel *item3TitleLabel;

@property (weak, nonatomic) IBOutlet UIButton *helpBtn;
@property (weak, nonatomic) IBOutlet UIButton *removeBtn;
@property (weak, nonatomic) IBOutlet UIButton *offBtn;

@property (nonatomic, assign) BOOL  isWrite;
// 0.没有设置  1.设置充电  2，设置放电  3.设置重启
@property (assign, nonatomic) NSInteger  setType;
@property (nonatomic, strong) NSTimer *queryTimer; //数据定时器

@property (nonatomic, assign) NSInteger queryCount;

@end

@implementation DeviceDCViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.topSpace.constant = IphoneX ? 54 : 20;
    self.isWrite = NO;
    self.setType = 0;

    self.titleLabel.text = NSLocalizedString(@"Control Center", nil);
    self.item1TitleLabel.text = NSLocalizedString(@"Discharge Switch", nil);
    self.item2TitleLabel.text = NSLocalizedString(@"Power saving mode", nil);
    self.item2DescLabel1.text = NSLocalizedString(@"Turn on the power conservation mode and use the [Forced Discharge] button to enable the engine.", nil);
    self.item2DescLabel2.text = NSLocalizedString(@"Forced discharge", nil);
    self.item3TitleLabel.text = NSLocalizedString(@"Heating auto mode", nil);
    [self.helpBtn setTitle:NSLocalizedString(@"Need Help", nil) forState:UIControlStateNormal];
    [self.removeBtn setTitle:[NSString stringWithFormat:@"  %@", NSLocalizedString(@"Remove Device", nil)] forState:UIControlStateNormal];
    [self.offBtn setTitle:[NSString stringWithFormat:@"  %@", NSLocalizedString(@"Power OFF", nil)] forState:UIControlStateNormal];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReciveData:) name:kBTDidReciveData object:nil];
    
    [self queryData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.queryTimer invalidate];
    self.queryTimer = nil;
}

- (void)queryData {
    WeakSelf
    self.queryTimer = [NSTimer scheduledTimerWithTimeInterval:2 repeats:YES block:^(NSTimer * _Nonnull timer) {
        if (weakSelf.isWrite) {
            return;
        }
        if (weakSelf.queryCount % 2 == 0) {
            [weakSelf readSwitchStatus];
        }else {
            [weakSelf queryBatteryOther];
        }
        weakSelf.queryCount ++;
    }];
}

- (IBAction)actionBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)actionCFD:(UIButton *)sender {
    sender.selected = !sender.selected;
    self.setType = 1;
    self.isWrite = YES;
    [ProgressHUD showActivityMessageInView:@"" timer:8];
    Byte bytes[8];
    bytes[0] = 0x01;
    bytes[1] = 0x06;
    bytes[2] = 0x11;
    bytes[3] = sender.isSelected ? 0x02 : 0x03;
    bytes[4] = 0x00;
    bytes[5] = 0x03;
    bytes[6] = 0x00;
    bytes[7] = 0x00;
    sleep(1);
    [[BTManager sharedBTManager] sendCommandWithCrc:bytes length:8];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.isWrite = NO;
        if (self.setType == 1) {
            self.cdfSW.selected = !self.cdfSW.selected;
            [ProgressHUD hideHUD];
            [ProgressHUD showSuccessMessage:NSLocalizedString(@"Set failed", nil)];
        }
    });
}

- (IBAction)actionJR:(UIButton *)sender {
    sender.selected = !sender.selected;
    self.setType = 2;
    self.isWrite = YES;
    [ProgressHUD showActivityMessageInView:@"" timer:8];
    Byte write_array[8];
    write_array[0] = 0x01;
    write_array[1] = 0x06;
    write_array[2] = 0x11;
    write_array[3] = sender.selected ? 0x02 : 0x03;
    write_array[4] = 0x00;
    write_array[5] = 0x0d;
    write_array[6] = 0x00;
    write_array[7] = 0x00;
    sleep(1);
    [[BTManager sharedBTManager] sendCommandWithCrc:write_array length:8];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.isWrite = NO;
        if (self.setType == 2) {
            self.cdjrSW.selected = !self.cdjrSW.selected;
            [ProgressHUD hideHUD];
            [ProgressHUD showSuccessMessage:NSLocalizedString(@"Set failed", nil)];
        }
    });
}

- (IBAction)actionRt:(UIButton *)sender {
    sender.selected = !sender.selected;
    self.restartH.constant =  sender.selected ? 172 : 90;
    self.restartTop.constant = sender.selected ? 20 : 32;
    self.restartLabel.hidden = !sender.selected;
    self.restartSW.hidden = !sender.selected;
    self.restartStateLabel.hidden = !sender.selected;
}

- (IBAction)actionRestart:(UIButton *)sender {
    sender.selected = !sender.selected;
    self.isWrite = YES;
    BOOL isOpen = sender.selected;
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Forced discharge", nil) message:NSLocalizedString(@"The current power of the device is low after forced discharge, please start the engine in time to replenish the power to avoid complete depletion of power.", nil) preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        self.isWrite = NO;
        self.restartSW.selected = !self.restartSW.selected;
        if (self.restartSW.selected) {
            self.restartStateLabel.backgroundColor = RGB16(0x91D140);
            self.restartStateLabel.layer.borderColor = [UIColor whiteColor].CGColor;
            self.restartStateLabel.layer.borderWidth = 1;
            self.restartStateLabel.textColor = [UIColor whiteColor];
        }else {
            self.restartStateLabel.backgroundColor = [UIColor whiteColor];
            self.restartStateLabel.layer.borderColor = RGB16(0x181820).CGColor;
            self.restartStateLabel.layer.borderWidth = 1;
            self.restartStateLabel.textColor = RGB16(0x91D140);
        }
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Confirm", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self setRestart:isOpen];
    }]];
    [self presentViewController:alertController animated:true completion:nil];
}

- (void)setRestart:(BOOL)isOpen {
    self.setType = 3;
    [ProgressHUD showActivityMessageInView:@"" timer:8];
    Byte write_array[8];
    write_array[0] = 0x01;
    write_array[1] = 0x06;
    write_array[2] = 0x11;
    write_array[3] = isOpen ? 0x02 : 0x03;
    write_array[4] = 0x00;
    write_array[5] = 0x0e;
    write_array[6] = 0x00;
    write_array[7] = 0x00;
    sleep(1);
    [[BTManager sharedBTManager] sendCommandWithCrc:write_array length:8];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.isWrite = NO;
        if (self.setType == 3) {
            self.restartSW.selected = !self.restartSW.selected;
            if (self.restartSW.selected) {
                self.restartStateLabel.backgroundColor = RGB16(0x91D140);
                self.restartStateLabel.layer.borderColor = [UIColor whiteColor].CGColor;
                self.restartStateLabel.layer.borderWidth = 1;
                self.restartStateLabel.textColor = [UIColor whiteColor];
            }else {
                self.restartStateLabel.backgroundColor = [UIColor whiteColor];
                self.restartStateLabel.layer.borderColor = RGB16(0x181820).CGColor;
                self.restartStateLabel.layer.borderWidth = 1;
                self.restartStateLabel.textColor = RGB16(0x91D140);
            }
            [ProgressHUD hideHUD];
            [ProgressHUD showSuccessMessage:NSLocalizedString(@"Set failed", nil)];
        }
    });
}

- (IBAction)actionOFF:(id)sender {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Power Off", nil) message:NSLocalizedString(@"1、Disconnect any chargers connected to the battery.\n2、The Bluetooth connection of the current device will be cut off.", nil) preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleCancel handler: nil]];
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Got it", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        Byte write_array[8];
        write_array[0] = 0x01;
        write_array[1] = 0x06;
        write_array[2] = 0x11;
        write_array[3] = 0x02;
        write_array[4] = 0x00;
        write_array[5] = 0x0A;
        write_array[6] = 0x00;
        write_array[7] = 0x00;
        [[BTManager sharedBTManager] sendCommandWithCrc:write_array length:8];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popToRootViewControllerAnimated:YES];
        });
    }]];
    [self presentViewController:alertController animated:true completion:nil];
}

- (IBAction)actionRemove:(id)sender {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"System hint", nil) message:NSLocalizedString(@"Are you sure you want to delete your account? This action will permanently delete your personal information and device connection information and cannot be restored.", nil) preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleCancel handler: nil]];
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Got it", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSString *listStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"BatteryBluList"] ?: @"";
        NSMutableArray *arr = [NSMutableArray array];
        if (listStr.length) {
            NSArray *dataArray = [BlutoothModel covertToModelList:listStr];
            [arr addObjectsFromArray:dataArray];
        }
        for (BlutoothModel *m in arr) {
            if ([m.uuid isEqualToString:self.model.uuid]) {
                [arr removeObject:m];
                break;
            }
        }
        [[NSUserDefaults standardUserDefaults] setObject:[BlutoothModel toJson:arr] forKey:@"BatteryBluList"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"BatteryBluListDidChanged" object:nil];
        [self.navigationController popToRootViewControllerAnimated:YES];
    }]];
    [self presentViewController:alertController animated:true completion:nil];
}

- (IBAction)actionHelp:(id)sender {
    HelpCenterViewController *vc = [[HelpCenterViewController alloc] initWithNibName:@"HelpCenterViewController" bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)readSwitchStatus {
    Byte write_array[8];
    write_array[0] = 0x01;
    write_array[1] = 0x03;
    write_array[2] = 0xd1;
    write_array[3] = 0x17;
    write_array[4] = 0x00;
    write_array[5] = 0x01;
    write_array[6] = 0x00;
    write_array[7] = 0x00;
    [[BTManager sharedBTManager] sendCommandWithCrc:write_array length:8];
}

- (void)queryBatteryOther {
    //主机读取电池其他信息
    Byte bytes[8];
    bytes[0] = 0x01;
    bytes[1] = 0x03;
    bytes[2] = 0xD1;
    bytes[3] = 0x15;
    bytes[4] = 0x00;
    bytes[5] = 0x0c;
    bytes[6] = 0x6d;
    bytes[7] = 0x37;
    [[BTManager sharedBTManager] sendCommand:bytes length:8];
}

- (void)didReciveData:(NSNotification *)notification {
    NSData *reciveData = notification.object;
    Byte *dataBytes = (Byte*)reciveData.bytes;
    if(dataBytes[2] == 0x02 && reciveData.length == 7) {
        NSInteger num = dataBytes[3] * 256 + dataBytes[4];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.cdjrSW.selected = (num >> 13) & 1;
            self.restartSW.selected = (num >> 14) & 1;
            if (self.restartSW.selected) {
                self.restartStateLabel.backgroundColor = RGB16(0x91D140);
                self.restartStateLabel.layer.borderColor = [UIColor whiteColor].CGColor;
                self.restartStateLabel.layer.borderWidth = 1;
                self.restartStateLabel.textColor = [UIColor whiteColor];
            }else {
                self.restartStateLabel.backgroundColor = [UIColor whiteColor];
                self.restartStateLabel.layer.borderColor = RGB16(0x181820).CGColor;
                self.restartStateLabel.layer.borderWidth = 1;
                self.restartStateLabel.textColor = RGB16(0x91D140);
            }
        });
    }else if (dataBytes[2] == 0x18) {
        NSInteger swStatus = dataBytes[7] * 256 + dataBytes[8];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.cdfSW.selected = (swStatus & 0x04) > 0 ? 1 : 0;
        });
    }else if (dataBytes[1] == 0x06) {
        [ProgressHUD hideHUD];
        if (self.setType == 5) {
            [ProgressHUD showSuccessMessage:NSLocalizedString(@"Password Cancel Succeeded", nil)];
        }else {
            [ProgressHUD showSuccessMessage:NSLocalizedString(@"Set successful", nil)];
        }
        self.setType = 0;
        self.isWrite = NO;
    }else if (dataBytes[1] == 0x10) {
        [ProgressHUD hideHUD];
        self.isWrite = NO;
        [ProgressHUD showSuccessMessage:NSLocalizedString(@"Set successful", nil)];
        self.setType = 0;
    }else if (dataBytes[1] == 0x90) {
        self.setType = 0;
        [ProgressHUD hideHUD];
        [ProgressHUD showSuccessMessage:NSLocalizedString(@"Set failed", nil)];
        self.isWrite = NO;
    }
}


@end
